# -*- coding:utf-8 -*-
# !/usr/bin/env python
# 作者：士超
# 创建：2020-06-29
# 更新：2020-06-29
# 用意：解析2号线
import os
import sys
import struct
import csv
import time
from datetime import datetime
from datetime import timedelta

sys.path.append("./package")
from const import const
from log import Log
# from MysqlHelp import mysql_helper
from MysqlHelp import _MySqlHelper


# 数据写入文件
def writeFile(fileName, dataNum):
    fff = open(fileName, 'a+', newline='', encoding='utf-8-sig')
    csv_writer = csv.writer(fff)
    csv_writer.writerow(dataNum)
    fff.close()


# BCD转换
def change(num):
    a = int(num)
    s = str(a // 16)
    g = str(a % 16)
    c = str(s + g)
    return c


# vDuration处理函数
def vDuration(bt):
    if bt:
        a = int(bt)
        typeNum = int(a // 4096)
        num = a - typeNum * 4096
        if typeNum == 1:
            typeStr = "秒"
        elif typeNum == 2:
            typeStr = "分钟"
        elif typeNum == 3:
            typeStr = "小时"
        elif typeNum == 4:
            typeStr = "日"
        elif typeNum == 5:
            typeStr = "周"
        elif typeNum == 7:
            typeStr = "年"
        else:
            typeStr = ""
        bt = "%d%s" % (num, typeStr)
    else:
        bt = '00'
    return bt


# 获取文件夹下所有文件
def get_all_file(rawdir):
    allfilelist = os.listdir(rawdir)
    for f in allfilelist:
        filepath = os.path.join(rawdir, f)
        if os.path.isdir(filepath):
            get_all_file(filepath)
        else:
            local_File.append(filepath)


def dataDeal(source_path, target_path, lineNum, typeStr, dbName):
    mysql_helper = _MySqlHelper(dbName)
    # 保存到日志文件中
    logName = lineNum + '#' + typeStr
    rq = time.strftime('%Y%m%d', time.localtime(time.time()))
    log = Log(logName, rq)
    # 获取数据文件名
    global local_File
    local_File = []
    get_all_file(source_path)
    # local_File = os.listdir(source_path)
    if not local_File:
        log.info('无数据文件的路径: %s' % source_path)
        return
    for FileName in local_File:
        # FileName = os.path.join(dataPath + file)
        # if not os.path.isfile(FileName):
        #     log.error('不是文件: %s' %dataPath)
        #     continue
        _, file = os.path.split(FileName)
        with open(FileName, mode='rb') as f:
            a = f.read(39)
#            print(len(a))
            if len(a) < 39 :
                continue
            transfer_header = struct.unpack('<1B2I12B1H6B1H2B1I2B', a)
            if transfer_header[5] not in [2, 3]:
                log.info('其他数据类型: ' + FileName)
                continue
            try:
                transfer_header_date = ''.join([change(i) for i in [transfer_header[k] for k in range(8, 15)]])
                transfer_header_lineid = change(transfer_header[17])
                transfer_header_station_number = change(transfer_header[18])
                b = f.read(28)
                public_header = struct.unpack('<3B2B1B7B1H1I1H7B', b)
                packet_type = public_header[1]
                public_header_lineid = change(public_header[3])
                public_header_station_number = change(public_header[4])
                public_header_date = ''.join([change(i) for i in [public_header[k] for k in range(6, 13)]])
                sql = ''
                if packet_type == 1:
                    while True:
                        fileName = target_path
                        c = f.read(10)
                        if len(c) < 10:
                            break
                        afc = struct.unpack('<7B1H1B', c)
                        operatorid = ''.join([change(i) for i in [afc[k] for k in range(3)]])
                        date_of_occurrence = ''.join([change(i) for i in [afc[k] for k in range(3, 7)]])
                        recorder_len = afc[7]
                        dataNum = [file + "\t", operatorid + "\t", date_of_occurrence + "\t", str(afc[-2]),
                                   str(afc[-1])]
                        d = f.read(56)
                        SysComHdr_t = struct.unpack('>3I4B3I4B6I', d)
                        for i in range(len(SysComHdr_t)):
                            if i == 1:
                                txnDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(SysComHdr_t[i])) + "\t"
                                dataNum.append(txnDateTime)
                                continue
                            if i == 16:
                                try:
                                    reconciliationDate = (datetime(1899, 12, 31) + timedelta(
                                        days=SysComHdr_t[i])).strftime("%Y%m%d") + "\t"
                                except Exception as e:
                                    reconciliationDate = str(SysComHdr_t[i]) + "\t"
                                dataNum.append(reconciliationDate)
                                continue
                            dataNum.append(str(SysComHdr_t[i]))
                        udType = SysComHdr_t[-2]
                        udSubtype = SysComHdr_t[-1]
                        # 3.1.1.1   TxnCardIssue
                        if udType == 1 and udSubtype == 3:
                            fileName += '0103.' + date_of_occurrence + '.csv'
                            sql = const.SQL0103
                            w = f.read(36)
                            cardData = struct.unpack('>6I1Q1I', w)
                            for u in range(len(cardData)):
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.2   TxnProductMultirideIssue
                        elif udType == 3 and udSubtype == 3:
                            fileName += '0303.' + date_of_occurrence + '.csv'
                            sql = const.SQL0303
                            w = f.read(120)
                            cardData = struct.unpack('>25I8B1Q1I', w)
                            # print(cardData)
                            for u in range(len(cardData)):
                                if u == 22:
                                    vStartDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vStartDateTime)
                                    continue
                                if u == 23:
                                    vEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vEndDateTime)
                                    continue
                                if u == 24:
                                    dataNum.append(vDuration(cardData[u]) + "\t")
                                    continue
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.3   TxnProductPassIssue
                        elif udType == 3 and udSubtype == 2:
                            fileName += '0302.' + date_of_occurrence + '.csv'
                            sql = const.SQL0302
                            w = f.read(116)
                            cardData = struct.unpack('>24I8B1Q1I', w)
                            # print(cardData)
                            for u in range(len(cardData)):
                                if u == 17:
                                    passEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(passEndDateTime)
                                    continue
                                if u == 21:
                                    vStartDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vStartDateTime)
                                    continue
                                if u == 22:
                                    vEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vEndDateTime)
                                    continue
                                if u == 23:
                                    dataNum.append(vDuration(cardData[u]) + "\t")
                                    continue
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.4   TxnProductPurseIssue
                        elif udType == 3 and udSubtype == 1:
                            fileName += '0301.' + date_of_occurrence + '.csv'
                            sql = const.SQL0301
                            w = f.read(116)
                            cardData = struct.unpack('>24I8B1Q1I', w)
                            # print(cardData)
                            for u in range(len(cardData)):
                                if u == 21:
                                    vStartDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vStartDateTime)
                                    continue
                                if u == 22:
                                    vEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vEndDateTime)
                                    continue
                                if u == 23:
                                    dataNum.append(vDuration(cardData[u]) + "\t")
                                    continue
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.5   TxnProductMultirideExitTicketIssue
                        elif udType == 3 and udSubtype == 121:
                            fileName += '0379.' + date_of_occurrence + '.csv'
                            sql = const.SQL0379
                            w = f.read(136)
                            cardData = struct.unpack('>25I8B4I1Q1I', w)
                            # print(cardData)
                            for u in range(len(cardData)):
                                if u == 22:
                                    vStartDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vStartDateTime)
                                    continue
                                if u == 23:
                                    vEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vEndDateTime)
                                    continue
                                if u == 24:
                                    dataNum.append(vDuration(cardData[u]) + "\t")
                                    continue
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.6   TxnProductMultirideAdd
                        elif udType == 3 and udSubtype == 12:
                            fileName += '030C.' + date_of_occurrence + '.csv'
                            sql = const.SQL030C
                            w = f.read(156)
                            cardData = struct.unpack('>25I8B9I1Q1I', w)
                            # print(cardData)
                            for u in range(len(cardData)):
                                if u == 22:
                                    vStartDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vStartDateTime)
                                    continue
                                if u == 23:
                                    vEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vEndDateTime)
                                    continue
                                if u == 24:
                                    dataNum.append(vDuration(cardData[u]) + "\t")
                                    continue
                                if u == 35:
                                    lavDate = (datetime(1899, 12, 31) + timedelta(days=SysComHdr_t[i])).strftime(
                                        "%Y%m%d") + "\t"
                                    dataNum.append(lavDate)
                                    continue
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.7   TxnProductPassAdd
                        elif udType == 3 and udSubtype == 11:
                            fileName += '030B.' + date_of_occurrence + '.csv'
                            sql = const.SQL030B
                            w = f.read(152)
                            cardData = struct.unpack('>24I8B9I1Q1I', w)
                            for u in range(len(cardData)):
                                if u == 21:
                                    vStartDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vStartDateTime)
                                    continue
                                if u == 22:
                                    vEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vEndDateTime)
                                    continue
                                if u == 23:
                                    dataNum.append(vDuration(cardData[u]) + "\t")
                                    continue
                                if u == 34:
                                    lavDate = (datetime(1899, 12, 31) + timedelta(days=SysComHdr_t[i])).strftime(
                                        "%Y%m%d") + "\t"
                                    dataNum.append(lavDate)
                                    continue
                                if u == 36:
                                    lavPassExpiryDateTime = time.strftime("%Y%m%d%H%M%S",
                                                                          time.localtime(cardData[u])) + "\t"
                                    dataNum.append(lavPassExpiryDateTime)
                                    continue
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.8   TxnProductPurseAdd
                        elif udType == 3 and udSubtype == 10:
                            fileName += '030A.' + date_of_occurrence + '.csv'
                            sql = const.SQL030A
                            w = f.read(152)
                            cardData = struct.unpack('>24I8B9I1Q1I', w)
                            for u in range(len(cardData)):
                                if u == 21:
                                    vStartDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vStartDateTime)
                                    continue
                                if u == 22:
                                    vEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vEndDateTime)
                                    continue
                                if u == 23:
                                    dataNum.append(vDuration(cardData[u]) + "\t")
                                    continue
                                if u == 34:
                                    lavDate = (datetime(1899, 12, 31) + timedelta(days=SysComHdr_t[i])).strftime(
                                        "%Y%m%d") + "\t"
                                    dataNum.append(lavDate)
                                    continue
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.9   TxnProductMultirideCompensationFare
                        elif udType == 3 and udSubtype == 120:
                            fileName += '0378.' + date_of_occurrence + '.csv'
                            sql = const.SQL0378
                            w = f.read(172)
                            # cardData = struct.unpack('>29I8B9I1Q1I', w)
                            cardData = struct.unpack('>18I12B8I8B9I1Q1I', w)
                            for u in range(len(cardData)):
                                if u == 35:
                                    vStartDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vStartDateTime)
                                    continue
                                if u == 36:
                                    vEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vEndDateTime)
                                    continue
                                if u == 37:
                                    dataNum.append(vDuration(cardData[u]) + "\t")
                                    continue
                                if u == 48:
                                    lavDate = (datetime(1899, 12, 31) + timedelta(days=SysComHdr_t[i])).strftime(
                                        "%Y%m%d") + "\t"
                                    dataNum.append(lavDate)
                                    continue
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.10  TxnProductPassCompensationFare
                        elif udType == 3 and udSubtype == 119:
                            fileName += '0377.' + date_of_occurrence + '.csv'
                            sql = const.SQL0377
                            w = f.read(168)
                            # cardData = struct.unpack('>28I8B9I1Q1I', w)
                            cardData = struct.unpack('>18I12B7I8B9I1Q1I', w)
                            for u in range(len(cardData)):
                                if u == 30:
                                    passEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(passEndDateTime)
                                    continue
                                if u == 34:
                                    vStartDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vStartDateTime)
                                    continue
                                if u == 35:
                                    vEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vEndDateTime)
                                    continue
                                if u == 36:
                                    dataNum.append(vDuration(cardData[u]) + "\t")
                                    continue
                                if u == 47:
                                    lavDate = (datetime(1899, 12, 31) + timedelta(days=SysComHdr_t[i])).strftime(
                                        "%Y%m%d") + "\t"
                                    dataNum.append(lavDate)
                                    continue
                                if u == 49:
                                    lavPassExpiryDateTime = time.strftime("%Y%m%d%H%M%S",
                                                                          time.localtime(cardData[u])) + "\t"
                                    dataNum.append(lavPassExpiryDateTime)
                                    continue
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.11 TxnProductPurseCompensationFare
                        elif udType == 3 and udSubtype == 118:
                            fileName += '0376.' + date_of_occurrence + '.csv'
                            sql = const.SQL0376
                            w = f.read(148)
                            # cardData = struct.unpack('>20I12B11I1Q1I', w)
                            cardData = struct.unpack('>18I12B13I1Q1I', w)
                            for u in range(len(cardData)):
                                if u == 36:
                                    lavDate = (datetime(1899, 12, 31) + timedelta(days=SysComHdr_t[i])).strftime(
                                        "%Y%m%d") + "\t"
                                    dataNum.append(lavDate)
                                    continue
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.4	PACC交易-TxnProductMultirideUseOnExit
                        elif udType == 3 and udSubtype == 93:
                            fileName += '035D.' + date_of_occurrence + '.csv'
                            sql = const.SQL035D
                            w = f.read(180)
                            # cardData = struct.unpack('>29I8B9I1Q1I', w)
                            cardData = struct.unpack('>18I12B5I8B14I1Q1I', w)
                            for u in range(len(cardData)):
                                if u == 33:
                                    vStartDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vStartDateTime)
                                    continue
                                if u == 34:
                                    vEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vEndDateTime)
                                    continue
                                if u == 35:
                                    dataNum.append(vDuration(cardData[u]) + "\t")
                                    continue
                                if u == 46:
                                    lavDate = (datetime(1899, 12, 31) + timedelta(days=SysComHdr_t[i])).strftime(
                                        "%Y%m%d") + "\t"
                                    dataNum.append(lavDate)
                                    continue
                                if u == 38:
                                    entryTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(entryTime)
                                    continue
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.5	PACC交易-TxnProductPassUseOnExit
                        elif udType == 3 and udSubtype == 92:
                            fileName += '035C.' + date_of_occurrence + '.csv'
                            sql = const.SQL035C
                            w = f.read(168)
                            # cardData = struct.unpack('>29I8B9I1Q1I', w)
                            cardData = struct.unpack('>18I12B4I8B12I1Q1I', w)
                            for u in range(len(cardData)):
                                if u == 32:
                                    vStartDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vStartDateTime)
                                    continue
                                if u == 33:
                                    vEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vEndDateTime)
                                    continue
                                if u == 34:
                                    dataNum.append(vDuration(cardData[u]) + "\t")
                                    continue
                                if u == 45:
                                    lavDate = (datetime(1899, 12, 31) + timedelta(days=SysComHdr_t[i])).strftime(
                                        "%Y%m%d") + "\t"
                                    dataNum.append(lavDate)
                                    continue
                                if u == 31:
                                    passEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(passEndDateTime)
                                    continue
                                if u == 52:
                                    entryTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(entryTime)
                                    continue
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.6	PACC交易-TxnProductPurseUseOnExit
                        elif udType == 3 and udSubtype == 91:
                            fileName += '035B.' + date_of_occurrence + '.csv'
                            sql = const.SQL035B
                            w = f.read(168)
                            # cardData = struct.unpack('>29I8B9I1Q1I', w)
                            cardData = struct.unpack('>18I12B18I1Q1I', w)
                            for u in range(len(cardData)):
                                if u == 37:
                                    lavDate = (datetime(1899, 12, 31) + timedelta(days=SysComHdr_t[i])).strftime(
                                        "%Y%m%d") + "\t"
                                    dataNum.append(lavDate)
                                    continue
                                if u == 44:
                                    entryTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(entryTime)
                                    continue
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.10	PACC交易-TxnProductDelayMultirideUseOnExit
                        elif udType == 3 and udSubtype == 113:
                            fileName += '0371.' + date_of_occurrence + '.csv'
                            sql = const.SQL0371
                            w = f.read(188)
                            # cardData = struct.unpack('>29I8B9I1Q1I', w)
                            cardData = struct.unpack('>18I12B5I8B16I1Q1I', w)
                            for u in range(len(cardData)):
                                if u == 46:
                                    lavDate = (datetime(1899, 12, 31) + timedelta(days=SysComHdr_t[i])).strftime(
                                        "%Y%m%d") + "\t"
                                    dataNum.append(lavDate)
                                    continue
                                if u == 53:
                                    entryTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(entryTime)
                                    continue
                                if u == 33:
                                    vStartDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vStartDateTime)
                                    continue
                                if u == 34:
                                    vEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vEndDateTime)
                                    continue
                                if u == 35:
                                    dataNum.append(vDuration(cardData[u]) + "\t")
                                    continue
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.11	PACC交易-TxnProductDelayPassUseOnExit
                        elif udType == 3 and udSubtype == 115:
                            fileName += '0373.' + date_of_occurrence + '.csv'
                            sql = const.SQL0373
                            w = f.read(180)
                            # cardData = struct.unpack('>29I8B9I1Q1I', w)
                            cardData = struct.unpack('>12I12B10I8B15I1Q1I', w)
                            for u in range(len(cardData)):

                                if u == 45:
                                    lavDate = (datetime(1899, 12, 31) + timedelta(days=SysComHdr_t[i])).strftime(
                                        "%Y%m%d") + "\t"
                                    dataNum.append(lavDate)
                                    continue
                                if u == 52:
                                    entryTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(entryTime)
                                    continue
                                if u == 31:
                                    passEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(passEndDateTime)
                                    continue
                                if u == 32:
                                    vStartDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vStartDateTime)
                                    continue
                                if u == 33:
                                    vEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vEndDateTime)
                                    continue
                                if u == 34:
                                    dataNum.append(vDuration(cardData[u]) + "\t")
                                    continue
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.12	PACC交易-TxnProductDelayPurseUseOnExit
                        elif udType == 3 and udSubtype == 117:
                            fileName += '0375.' + date_of_occurrence + '.csv'
                            sql = const.SQL0375
                            w = f.read(176)
                            # cardData = struct.unpack('>29I8B9I1Q1I', w)
                            cardData = struct.unpack('>12I12B26I1Q1I', w)
                            for u in range(len(cardData)):

                                if u == 37:
                                    lavDate = (datetime(1899, 12, 31) + timedelta(days=SysComHdr_t[i])).strftime(
                                        "%Y%m%d") + "\t"
                                    dataNum.append(lavDate)
                                    continue
                                if u == 44:
                                    entryTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(entryTime)
                                    continue
                                if u == 47:
                                    delayDate = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(delayDate)
                                    continue
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.12  TxnCardDepositReceipt
                        elif udType == 1 and udSubtype == 9:
                            fileName += '0109.' + date_of_occurrence + '.csv'
                            sql = const.SQL0109
                            w = f.read(44)
                            cardData = struct.unpack('>8I1Q1I', w)
                            for u in range(len(cardData)):
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.13  TxnCardholderFee
                        elif udType == 4 and udSubtype == 34:
                            fileName += '0422.' + date_of_occurrence + '.csv'
                            sql = const.SQL0422
                            w = f.read(64)
                            cardData = struct.unpack('>13I1Q1I', w)
                            for u in range(len(cardData)):
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.14  TxnCardFee
                        elif udType == 1 and udSubtype == 22:
                            fileName += '0116.' + date_of_occurrence + '.csv'
                            sql = const.SQL0116
                            w = f.read(44)
                            cardData = struct.unpack('>8I1Q1I', w)
                            for u in range(len(cardData)):
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.15  TxnCardRefund
                        elif udType == 1 and udSubtype == 10:
                            fileName += '010A.' + date_of_occurrence + '.csv'
                            sql = const.SQL010A
                            w = f.read(68)
                            cardData = struct.unpack('>14I1Q1I', w)
                            for u in range(len(cardData)):
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.16  TxnProductMultirideRefund
                        elif udType == 3 and udSubtype == 28:
                            fileName += '031C.' + date_of_occurrence + '.csv'
                            sql = const.SQL031C
                            w = f.read(156)
                            cardData = struct.unpack('>36I1Q1I', w)
                            for u in range(len(cardData)):
                                if u == 28:
                                    lavDate = (datetime(1899, 12, 31) + timedelta(days=SysComHdr_t[i])).strftime(
                                        "%Y%m%d") + "\t"
                                    dataNum.append(lavDate)
                                    continue
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.17  TxnProductPassRefund
                        elif udType == 3 and udSubtype == 27:
                            fileName += '031B.' + date_of_occurrence + '.csv'
                            sql = const.SQL031B
                            w = f.read(152)
                            cardData = struct.unpack('>35I1Q1I', w)
                            for u in range(len(cardData)):
                                if u == 27:
                                    lavDate = (datetime(1899, 12, 31) + timedelta(days=SysComHdr_t[i])).strftime(
                                        "%Y%m%d") + "\t"
                                    dataNum.append(lavDate)
                                    continue
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.18  TxnProductPurseRefund
                        elif udType == 3 and udSubtype == 26:
                            fileName += '031A.' + date_of_occurrence + '.csv'
                            sql = const.SQL031A
                            w = f.read(152)
                            cardData = struct.unpack('>35I1Q1I', w)
                            for u in range(len(cardData)):
                                if u == 27:
                                    lavDate = (datetime(1899, 12, 31) + timedelta(days=SysComHdr_t[i])).strftime(
                                        "%Y%m%d") + "\t"
                                    dataNum.append(lavDate)
                                    continue
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.19  TxnCardDepositReceiptRefund
                        elif udType == 1 and udSubtype == 39:
                            fileName += '0127.' + date_of_occurrence + '.csv'
                            sql = const.SQL0127
                            w = f.read(44)
                            cardData = struct.unpack('>8I1Q1I', w)
                            for u in range(len(cardData)):
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.20  TxnProductMultirideIssueReverse
                        elif udType == 3 and udSubtype == 79:
                            fileName += '034F.' + date_of_occurrence + '.csv'
                            sql = const.SQL034F
                            w = f.read(124)
                            cardData = struct.unpack('>25I8B1I1Q1I', w)
                            for u in range(len(cardData)):
                                if u == 23:
                                    vStartDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vStartDateTime)
                                    continue
                                if u == 24:
                                    vEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vEndDateTime)
                                    continue
                                if u == 25:
                                    dataNum.append(vDuration(cardData[u]) + "\t")
                                    continue
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.21  TxnProductPassIssueReverse
                        elif udType == 3 and udSubtype == 80:
                            fileName += '0350.' + date_of_occurrence + '.csv'
                            sql = const.SQL0350
                            w = f.read(120)
                            cardData = struct.unpack('>24I8B1I1Q1I', w)
                            for u in range(len(cardData)):
                                if u == 17:
                                    passEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(passEndDateTime)
                                    continue
                                if u == 21:
                                    vStartDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vStartDateTime)
                                    continue
                                if u == 22:
                                    vEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vEndDateTime)
                                    continue
                                if u == 23:
                                    dataNum.append(vDuration(cardData[u]) + "\t")
                                    continue
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.22  TxnProductPurseIssueReverse
                        elif udType == 3 and udSubtype == 81:
                            fileName += '0351.' + date_of_occurrence + '.csv'
                            sql = const.SQL0351
                            w = f.read(120)
                            cardData = struct.unpack('>24I8B1I1Q1I', w)
                            for u in range(len(cardData)):
                                if u == 21:
                                    vStartDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vStartDateTime)
                                    continue
                                if u == 22:
                                    vEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vEndDateTime)
                                    continue
                                if u == 23:
                                    dataNum.append(vDuration(cardData[u]) + "\t")
                                    continue
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.23  TxnProductMultirideAddReverse
                        elif udType == 3 and udSubtype == 18:
                            fileName += '0312.' + date_of_occurrence + '.csv'
                            sql = const.SQL0312
                            w = f.read(144)
                            cardData = struct.unpack('>25I8B9I', w)
                            for u in range(len(cardData)):
                                if u == 22:
                                    vStartDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vStartDateTime)
                                    continue
                                if u == 23:
                                    vEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vEndDateTime)
                                    continue
                                if u == 24:
                                    dataNum.append(vDuration(cardData[u]) + "\t")
                                    continue
                                if u == 35:
                                    lavDate = (datetime(1899, 12, 31) + timedelta(days=SysComHdr_t[i])).strftime(
                                        "%Y%m%d") + "\t"
                                    dataNum.append(lavDate)
                                    continue
                                dataNum.append(str(cardData[u]))
                            m = f.read(12)
                            operatorid_struct = struct.unpack('>12B', w)
                            operatorid1 = ''.join([change(i) for i in [operatorid_struct[k] for k in range(12)]])
                            dataNum.append(operatorid1 + "\t")
                            n = f.read(16)
                            SysSecurityHdr_t = struct.unpack('>1I1Q1I', w)
                            for u in range(len(SysSecurityHdr_t)):
                                dataNum.append(str(SysSecurityHdr_t[u]))
                        # 3.1.1.24  TxnProductPassAddReverse
                        elif udType == 3 and udSubtype == 17:
                            fileName += '0311.' + date_of_occurrence + '.csv'
                            sql = const.SQL0311
                            w = f.read(140)
                            cardData = struct.unpack('>24I8B9I', w)
                            for u in range(len(cardData)):
                                if u == 17:
                                    passEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(passEndDateTime)
                                    continue
                                if u == 21:
                                    vStartDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vStartDateTime)
                                    continue
                                if u == 22:
                                    vEndDateTime = time.strftime("%Y%m%d%H%M%S", time.localtime(cardData[u])) + "\t"
                                    dataNum.append(vEndDateTime)
                                    continue
                                if u == 23:
                                    dataNum.append(vDuration(cardData[u]) + "\t")
                                    continue
                                if u == 34:
                                    lavDate = (datetime(1899, 12, 31) + timedelta(days=SysComHdr_t[i])).strftime(
                                        "%Y%m%d") + "\t"
                                    dataNum.append(lavDate)
                                    continue
                                dataNum.append(str(cardData[u]))
                            m = f.read(12)
                            operatorid_struct = struct.unpack('>12B', w)
                            operatorid1 = ''.join([change(i) for i in [operatorid_struct[k] for k in range(12)]])
                            dataNum.append(operatorid1 + "\t")
                            n = f.read(16)
                            SysSecurityHdr_t = struct.unpack('>1I1Q1I', w)
                            for u in range(len(SysSecurityHdr_t)):
                                dataNum.append(str(SysSecurityHdr_t[u]))
                        # 3.1.1.25  TxnProductPurseAddReverse
                        elif udType == 3 and udSubtype == 16:
                            fileName += '0310.' + date_of_occurrence + '.csv'
                            sql = const.SQL0310
                            w = f.read(120)
                            cardData = struct.unpack('>8I1Q1I', w)
                            for u in range(len(cardData)):
                                if u == 23:
                                    lavDate = (datetime(1899, 12, 31) + timedelta(days=SysComHdr_t[i])).strftime(
                                        "%Y%m%d") + "\t"
                                    dataNum.append(lavDate)
                                    continue
                                dataNum.append(str(cardData[u]))
                            m = f.read(12)
                            operatorid_struct = struct.unpack('>12B', w)
                            operatorid1 = ''.join([change(i) for i in [operatorid_struct[k] for k in range(12)]])
                            dataNum.append(operatorid1 + "\t")
                            n = f.read(16)
                            SysSecurityHdr_t = struct.unpack('>1I1Q1I', w)
                            for u in range(len(SysSecurityHdr_t)):
                                dataNum.append(str(SysSecurityHdr_t[u]))
                        # 3.1.1.26  TxnCardDepositReceiptReverse
                        elif udType == 1 and udSubtype == 32:
                            fileName += '0120' + date_of_occurrence + '.csv'
                            sql = const.SQL0120
                            w = f.read(48)
                            cardData = struct.unpack('>9I1Q1I', w)
                            for u in range(len(cardData)):
                                dataNum.append(str(cardData[u]))
                        # 3.1.1.27  TxnCardFeeReverse
                        elif udType == 1 and udSubtype == 33:
                            fileName += '0121' + date_of_occurrence + '.csv'
                            sql = const.SQL0121
                            w = f.read(48)
                            cardData = struct.unpack('>9I1Q1I', w)
                            for u in range(len(cardData)):
                                dataNum.append(str(cardData[u]))
                        # 2.1.3.1   ACC交易
                        elif udType == 36:
                            if udSubtype == 1:
                                fileName += '2401.' + date_of_occurrence + '.csv'
                                sql = const.SQL2401
                            elif udSubtype == 2:
                                fileName += '2402.' + date_of_occurrence + '.csv'
                                sql = const.SQL2402
                            elif udSubtype == 3:
                                fileName += '2403.' + date_of_occurrence + '.csv'
                                sql = const.SQL2403
                            else:
                                # notype.write(FileName+'\n')
                                log.warning('ACC交易数据: ' + file + ',' + str(udType) + ',' + str(udSubtype))
                                break
                            w = f.read(8)
                            productIssuerId = struct.unpack('>2I', w)
                            for u in productIssuerId:
                                dataNum.append(str(u))
                            p = f.read(392)
                            Module_code = struct.unpack('>392B', p)
                            dataNum.append(''.join([chr(i) for i in [Module_code[k] for k in range(4)]]) + "\t")
                            dataNum.append(''.join([chr(i) for i in [Module_code[k] for k in range(4, 18)]]) + "\t")
                            dataNum.append(''.join([chr(i) for i in [Module_code[k] for k in range(18, 26)]]) + "\t")
                            dataNum.append(''.join([chr(i) for i in [Module_code[k] for k in range(26, 28)]]) + "\t")
                            dataNum.append(''.join([chr(i) for i in [Module_code[k] for k in range(28, 36)]]) + "\t")
                            #dataNum.append(''.join([chr(i) for i in [Module_code[k] for k in range(30, 32)]])+"\t")
                            #dataNum.append(''.join([chr(i) for i in [Module_code[k] for k in range(32, 34)]])+"\t")
                            #dataNum.append(''.join([chr(i) for i in [Module_code[k] for k in range(34, 36)]])+"\t")
                            dataNum.append(chr(Module_code[36]) + "\t")
                            dataNum.append(''.join([chr(i) for i in [Module_code[k] for k in range(37, 53)]]) + "\t")
                            dataNum.append(chr(Module_code[53]) + "\t")
                            dataNum.append(''.join([chr(i) for i in [Module_code[k] for k in range(54, 118)]]) + "\t")
                            dataNum.append(''.join([chr(i) for i in [Module_code[k] for k in range(118, 126)]]) + "\t")
                            dataNum.append(''.join([chr(i) for i in [Module_code[k] for k in range(126, 140)]]) + "\t")
                            dataNum.append(''.join([chr(i) for i in [Module_code[k] for k in range(140, 154)]]) + "\t")
                            dataNum.append(''.join([chr(i) for i in [Module_code[k] for k in range(154, 156)]]) + "\t")
                            dataNum.append(''.join([chr(i) for i in [Module_code[k] for k in range(156, 188)]]) + "\t")
                            dataNum.append(''.join([chr(i) for i in [Module_code[k] for k in range(188, 252)]]) + "\t")
                            dataNum.append(''.join([chr(i) for i in [Module_code[k] for k in range(252, 268)]]) + "\t")
                            dataNum.append(''.join([chr(i) for i in [Module_code[k] for k in range(268, 300)]]) + "\t")
                            dataNum.append(''.join([chr(i) for i in [Module_code[k] for k in range(300, 308)]]) + "\t")
                            dataNum.append(''.join([chr(i) for i in [Module_code[k] for k in range(308, 322)]]) + "\t")
                            dataNum.append(''.join([chr(i) for i in [Module_code[k] for k in range(322, 386)]]) + "\t")
                            dataNum.append(''.join([chr(i) for i in [Module_code[k] for k in range(386, 392)]]) + "\t")
                        else:
                            if recorder_len > 66:
                                e = f.read(recorder_len - 66)
                            # notype.write(FileName+','+str(udType)+','+str(udSubtype)+'\n')
                            log.warning('packet_type=1时: ' + file + ',' + str(udType) + ',' + str(udSubtype))
                            continue
                        if sql:
                            writeFile(fileName, dataNum)
                            mysql_helper.execute(sql, dataNum)
                elif packet_type == 2:
                    while True:
                        fileName = target_path
                        c = f.read(10)
                        if len(c) < 10:
                            break
                        afc = struct.unpack('<7B1H1B', c)
                        operatorid = ''.join([change(i) for i in [afc[k] for k in range(3)]])
                        date_of_occurrence = ''.join([change(i) for i in [afc[k] for k in range(3, 7)]])
                        dataNum = ["\t" + file, "\t" + operatorid, "\t" + date_of_occurrence, str(afc[-2]),
                                   str(afc[-1])]
                        recorder_len = afc[7]
                        d = f.read(6)
                        SysComHdr_t = struct.unpack('<2B1I', d)
                        udSubtype = SysComHdr_t[0]
                        udType = SysComHdr_t[1]
                        for i in SysComHdr_t:
                            dataNum.append(str(i))
                        # 长安通刷卡
                        if udType == 33:
                            sql = const.SQL0C21
                            if udSubtype == 12:
                                fileName += '0C21.' + date_of_occurrence + '.csv'
                            elif udSubtype == 13:
                                fileName += '0D21.' + date_of_occurrence + '.csv'
                            elif udSubtype == 14:
                                fileName += '0E21.' + date_of_occurrence + '.csv'
                            elif udSubtype == 15:
                                fileName += '0F21.' + date_of_occurrence + '.csv'
                            elif udSubtype == 17:
                                fileName += '1121.' + date_of_occurrence + '.csv'
                            elif udSubtype == 22:
                                fileName += '1621.' + date_of_occurrence + '.csv'
                            elif udSubtype == 33:
                                fileName += '2121.' + date_of_occurrence + '.csv'
                            else:
                                fileName += '0001.' + date_of_occurrence + '.csv'
                            e = f.read(14)
                            PosId_SamId = struct.unpack('<14B', e)
                            PosId = ''.join([change(i) for i in [PosId_SamId[k] for k in range(6)]])
                            SamId = ''.join([change(i) for i in [PosId_SamId[k] for k in range(6, 14)]])
                            dataNum.append("\t" + PosId)
                            dataNum.append("\t" + SamId)
                            g = f.read(8)
                            SamSeq = struct.unpack('<1I4B', g)
                            for i in range(len(SamSeq)):
                                if i == 2 or i == 3:
                                    dataNum.append("\t" + change(SamSeq[i]))
                                else:
                                    dataNum.append(str(SamSeq[i]))
                            h = f.read(13)
                            PosOperId_CardId = struct.unpack('<13B', h)
                            PosOperId = ''.join([change(i) for i in [PosOperId_CardId[k] for k in range(3)]])
                            CityCode = ''.join([change(i) for i in [PosOperId_CardId[k] for k in range(3, 5)]])
                            CardId = ''.join([change(i) for i in [PosOperId_CardId[k] for k in range(5, 13)]])
                            dataNum.append("\t" + PosOperId)
                            dataNum.append("\t" + CityCode)
                            dataNum.append("\t" + CardId)
                            j = f.read(22)
                            CardCsn_OrigAmt = struct.unpack('<1I1H3B2I1B1I', j)
                            for i in range(len(CardCsn_OrigAmt)):
                                if i in [3, 4, 7]:
                                    dataNum.append("\t" + change(CardCsn_OrigAmt[i]))
                                else:
                                    dataNum.append(str(CardCsn_OrigAmt[i]))
                            k = f.read(7)
                            TxnDate_TxnTime = struct.unpack('<7B', k)
                            TxnDate = ''.join([change(i) for i in [TxnDate_TxnTime[k] for k in range(4)]])
                            TxnTime = ''.join([change(i) for i in [TxnDate_TxnTime[k] for k in range(4, 7)]])
                            dataNum.append("\t" + TxnDate)
                            dataNum.append("\t" + TxnTime)
                            l = f.read(29)
                            TAC_upStationId = struct.unpack('<1I1B6I', l)
                            for i in range(len(TAC_upStationId)):
                                if i == 6:
                                    dataNum.append(
                                        "\t" + time.strftime("%Y%m%d%H%M%S", time.localtime(TAC_upStationId[i])))
                                else:
                                    dataNum.append(str(TAC_upStationId[i]))
                            o = f.read(4)
                            Expiration_date = struct.unpack('<4B', o)
                            Expiration = ''.join([change(i) for i in [Expiration_date[k] for k in range(4)]])
                            dataNum.append("\t" + Expiration)
                            r = f.read(9)
                            final_tuple = struct.unpack('<2I1B', r)
                            for i in range(len(final_tuple)):
                                dataNum.append(str(final_tuple[i]))
                        # 长安通售充
                        elif udType == 8:
                            if udSubtype == 14:
                                fileName += '0E08.' + date_of_occurrence + '.csv'
                                sql = const.SQL0E08
                            elif udSubtype == 15:
                                fileName += '0F08.' + date_of_occurrence + '.csv'
                                sql = const.SQL0F08
                            else:
                                fileName += '0002.' + date_of_occurrence + '.csv'
                            e = f.read(14)
                            PosId_SamId = struct.unpack('<14B', e)
                            PosId = ''.join([change(i) for i in [PosId_SamId[k] for k in range(6)]])
                            SamId = ''.join([change(i) for i in [PosId_SamId[k] for k in range(6, 14)]])
                            dataNum.append("\t" + PosId)
                            dataNum.append("\t" + SamId)
                            g = f.read(8)
                            SamSeq = struct.unpack('<1I4B', g)
                            for i in range(len(SamSeq)):
                                if i in [2, 3]:
                                    dataNum.append("\t" + change(SamSeq[i]))
                                else:
                                    dataNum.append(str(SamSeq[i]))
                            h = f.read(13)
                            PosOperId_CardId = struct.unpack('<13B', h)
                            PosOperId = ''.join([change(i) for i in [PosOperId_CardId[k] for k in range(3)]])
                            CityCode = ''.join([change(i) for i in [PosOperId_CardId[k] for k in range(3, 5)]])
                            CardId = ''.join([change(i) for i in [PosOperId_CardId[k] for k in range(5, 13)]])
                            dataNum.append("\t" + PosOperId)
                            dataNum.append("\t" + CityCode)
                            dataNum.append("\t" + CardId)
                            j = f.read(26)
                            CardCsn_AftBalance = struct.unpack('<1I1H4B4I', j)  # [3, 4, 5]
                            for i in range(len(CardCsn_AftBalance)):
                                if i in [3, 4, 5]:
                                    dataNum.append("\t" + change(CardCsn_AftBalance[i]))
                                else:
                                    dataNum.append(str(CardCsn_AftBalance[i]))
                            k = f.read(29)
                            SaleDate_serial_number = struct.unpack('<29B', k)
                            SaleDate = ''.join([change(i) for i in [SaleDate_serial_number[k] for k in range(4)]])
                            SaleMode = str(SaleDate_serial_number[4])
                            CardValDate = ''.join([change(i) for i in [SaleDate_serial_number[k] for k in range(5, 9)]])
                            TxnDate = ''.join([change(i) for i in [SaleDate_serial_number[k] for k in range(9, 13)]])
                            TxnTime = ''.join([change(i) for i in [SaleDate_serial_number[k] for k in range(13, 16)]])
                            CrdVerNo = str(SaleDate_serial_number[16])
                            BatchNo = ''.join([change(i) for i in [SaleDate_serial_number[k] for k in range(17, 20)]])
                            serial_number = ''.join(
                                [change(i) for i in [SaleDate_serial_number[k] for k in range(20, 29)]])
                            dataNum.append("\t" + SaleDate)
                            dataNum.append(SaleMode)
                            dataNum.append("\t" + CardValDate)
                            dataNum.append("\t" + TxnDate)
                            dataNum.append("\t" + TxnTime)
                            dataNum.append(CrdVerNo)
                            dataNum.append("\t" + BatchNo)
                            dataNum.append("\t" + serial_number)
                            q = f.read(45)
                            final_tuple = struct.unpack('<1I1H6B1I1H7B5I', q)
                            dataNum.append(str(final_tuple[0]))
                            dataNum.append(str(final_tuple[1]))
                            Termid = ''.join([change(i) for i in [final_tuple[k] for k in range(2, 8)]])
                            dataNum.append("\t" + Termid)
                            dataNum.append(str(final_tuple[8]))
                            dataNum.append(str(final_tuple[9]))
                            transaction_hour = ''.join([change(i) for i in [final_tuple[k] for k in range(10, 17)]])
                            dataNum.append("\t" + transaction_hour)
                            dataNum.append(str(final_tuple[17]))
                            dataNum.append(str(final_tuple[18]))
                            dataNum.append(str(final_tuple[19]))
                            dataNum.append(str(final_tuple[20]))
                            dataNum.append(str(final_tuple[21]))
                        # 交通卡本地卡非联机交易
                        elif udType == 34:
                            sql = const.SQL0C22
                            if udSubtype == 12:
                                fileName += '0C22.' + date_of_occurrence + '.csv'
                            elif udSubtype == 13:
                                fileName += '0D22.' + date_of_occurrence + '.csv'
                            elif udSubtype == 14:
                                fileName += '0E22.' + date_of_occurrence + '.csv'
                            elif udSubtype == 15:
                                fileName += '0F22.' + date_of_occurrence + '.csv'
                            elif udSubtype == 17:
                                fileName += '1122.' + date_of_occurrence + '.csv'
                            elif udSubtype == 22:
                                fileName += '1622.' + date_of_occurrence + '.csv'
                            else:
                                fileName += '0003.' + date_of_occurrence + '.csv'
                            e = f.read(14)
                            PosId_SamId = struct.unpack('<14B', e)
                            PosId = ''.join([change(i) for i in [PosId_SamId[k] for k in range(6)]])
                            SamId = ''.join([change(i) for i in [PosId_SamId[k] for k in range(6, 14)]])
                            dataNum.append("\t" + PosId)
                            dataNum.append("\t" + SamId)
                            g = f.read(8)
                            SamSeq = struct.unpack('<1I4B', g)
                            for i in range(len(SamSeq)):
                                if i in [2, 3]:
                                    dataNum.append("\t" + change(SamSeq[i]))
                                else:
                                    dataNum.append(str(SamSeq[i]))
                            h = f.read(13)
                            PosOperId_CardId = struct.unpack('<13B', h)
                            PosOperId = ''.join([change(i) for i in [PosOperId_CardId[k] for k in range(3)]])
                            CardId = ''.join([change(i) for i in [PosOperId_CardId[k] for k in range(3, 13)]])
                            dataNum.append("\t" + PosOperId)
                            dataNum.append("\t" + CardId)
                            j = f.read(22)
                            CardCsn_OrigAmt = struct.unpack('<1I1H1B2B2I1B1I', j)
                            for i in range(len(CardCsn_OrigAmt)):
                                if i == 7 or i == 3 or i == 4:
                                    dataNum.append("\t" + change(CardCsn_OrigAmt[i]))
                                else:
                                    dataNum.append(str(CardCsn_OrigAmt[i]))
                            k = f.read(7)
                            TxnDate_TxnTime = struct.unpack('<7B', k)
                            TxnDate = ''.join([change(i) for i in [TxnDate_TxnTime[k] for k in range(4)]])
                            TxnTime = ''.join([change(i) for i in [TxnDate_TxnTime[k] for k in range(4, 7)]])
                            dataNum.append("\t" + TxnDate)
                            dataNum.append("\t" + TxnTime)
                            l = f.read(29)
                            TAC_upStationId = struct.unpack('<1I1B6I', l)
                            for i in range(len(TAC_upStationId)):
                                if i == 6:
                                    dataNum.append(
                                        "\t" + time.strftime("%Y%m%d%H%M%S", time.localtime(TAC_upStationId[i])))
                                else:
                                    dataNum.append(str(TAC_upStationId[i]))
                            o = f.read(4)
                            Expiration_date = struct.unpack('<4B', o)
                            Expiration = ''.join([change(i) for i in [Expiration_date[k] for k in range(4)]])
                            dataNum.append("\t" + Expiration)
                            p = f.read(9)
                            final_4 = struct.unpack('<2I1B', p)
                            for i in range(len(final_4)):
                                dataNum.append(str(final_4[i]))
                            q = f.read(11)  # ASCII
                            final_3 = struct.unpack('<11B', q)
                            InstIssue = ''.join([chr(i) for i in final_3])
                            dataNum.append("\t" + InstIssue)
                            w = f.read(8)
                            final_2 = struct.unpack('<8B', w)
                            Merchant_identifier = ''.join([change(i) for i in [final_2[k] for k in range(4)]])
                            Merchant_type = ''.join([change(i) for i in [final_2[k] for k in range(4, 6)]])
                            CityCode = ''.join([change(i) for i in [final_2[k] for k in range(6, 8)]])
                            dataNum.append("\t" + Merchant_identifier)
                            dataNum.append("\t" + Merchant_type)
                            dataNum.append("\t" + CityCode)
                            t = f.read(2)
                            final_1 = struct.unpack('<2B', t)
                            for i in final_1:
                                dataNum.append(str(i))
                            tt = f.read(10)
                            final_0 = struct.unpack('<10B', tt)
                            # dataNum.append("\t"+''.join([change(i) for i in final_0]))
                            dataNum.append("\t" + ''.join(
                                ['{0:0>2}'.format(str(hex(i)).upper()[2:]) for i in [final_0[k] for k in range(10)]]))
                        # 交通卡异地卡非联机交易
                        elif udType == 35:
                            sql = const.SQL0C23
                            if udSubtype == 12:
                                fileName += '0C23.' + date_of_occurrence + '.csv'
                            elif udSubtype == 13:
                                fileName += '0D23.' + date_of_occurrence + '.csv'
                            elif udSubtype == 14:
                                fileName += '0E23.' + date_of_occurrence + '.csv'
                            elif udSubtype == 15:
                                fileName += '0F23.' + date_of_occurrence + '.csv'
                            elif udSubtype == 17:
                                fileName += '1123.' + date_of_occurrence + '.csv'
                            elif udSubtype == 22:
                                fileName += '1623.' + date_of_occurrence + '.csv'
                            else:
                                fileName += '0004.' + date_of_occurrence + '.csv'
                            e = f.read(14)
                            PosId_SamId = struct.unpack('<14B', e)
                            PosId = ''.join([change(i) for i in [PosId_SamId[k] for k in range(6)]])
                            SamId = ''.join([change(i) for i in [PosId_SamId[k] for k in range(6, 14)]])
                            dataNum.append("\t" + PosId)
                            dataNum.append("\t" + SamId)
                            g = f.read(8)
                            SamSeq = struct.unpack('<1I4B', g)
                            for i in range(len(SamSeq)):
                                if i in [2, 3]:
                                    dataNum.append("\t" + change(SamSeq[i]))
                                else:
                                    dataNum.append(str(SamSeq[i]))
                            h = f.read(13)
                            PosOperId_CardId = struct.unpack('<13B', h)
                            PosOperId = ''.join([change(i) for i in [PosOperId_CardId[k] for k in range(3)]])
                            CardId = ''.join([change(i) for i in [PosOperId_CardId[k] for k in range(3, 13)]])
                            dataNum.append("\t" + PosOperId)
                            dataNum.append("\t" + CardId)
                            j = f.read(22)
                            CardCsn_OrigAmt = struct.unpack('<1I1H1B2B2I1B1I', j)
                            for i in range(len(CardCsn_OrigAmt)):
                                if i == 7 or i == 3 or i == 4:
                                    dataNum.append("\t" + change(CardCsn_OrigAmt[i]))
                                else:
                                    dataNum.append(str(CardCsn_OrigAmt[i]))
                            k = f.read(7)
                            TxnDate_TxnTime = struct.unpack('<7B', k)
                            TxnDate = ''.join([change(i) for i in [TxnDate_TxnTime[k] for k in range(4)]])
                            TxnTime = ''.join([change(i) for i in [TxnDate_TxnTime[k] for k in range(4, 7)]])
                            dataNum.append("\t" + TxnDate)
                            dataNum.append("\t" + TxnTime)
                            l = f.read(29)
                            TAC_upStationId = struct.unpack('<1I1B6I', l)
                            for i in range(len(TAC_upStationId)):
                                if i == 6:
                                    dataNum.append(
                                        "\t" + time.strftime("%Y%m%d%H%M%S", time.localtime(TAC_upStationId[i])))
                                else:
                                    dataNum.append(str(TAC_upStationId[i]))
                            o = f.read(4)
                            Expiration_date = struct.unpack('<4B', o)
                            Expiration = ''.join([change(i) for i in [Expiration_date[k] for k in range(4)]])
                            dataNum.append("\t" + Expiration)
                            p = f.read(9)
                            final_4 = struct.unpack('<2I1B', p)
                            for i in range(len(final_4)):
                                dataNum.append(str(final_4[i]))
                            q = f.read(11)  # ASCII
                            final_3 = struct.unpack('<11B', q)
                            InstIssue = ''.join([chr(i) for i in final_3])
                            dataNum.append("\t" + InstIssue)
                            w = f.read(8)
                            final_2 = struct.unpack('<8B', w)
                            Merchant_identifier = ''.join([change(i) for i in [final_2[k] for k in range(4)]])
                            Merchant_type = ''.join([change(i) for i in [final_2[k] for k in range(4, 6)]])
                            CityCode = ''.join([change(i) for i in [final_2[k] for k in range(6, 8)]])
                            dataNum.append("\t" + Merchant_identifier)
                            dataNum.append("\t" + Merchant_type)
                            dataNum.append("\t" + CityCode)
                            m = f.read(5)
                            final_1 = struct.unpack('<5B', m)
                            for i in final_1:
                                dataNum.append(str(i))
                            tt = f.read(10)
                            final_0 = struct.unpack('<10B', tt)
                            # dataNum.append("\t"+''.join([change(i) for i in final_0]))
                            dataNum.append("\t" + ''.join(
                                ['{0:0>2}'.format(str(hex(i)).upper()[2:]) for i in [final_0[k] for k in range(10)]]))
                        else:
                            if recorder_len > 16:
                                e = f.read(recorder_len - 16)
                            log.warning('packet_type=2时: ' + file + ',' + str(udType) + ',' + str(udSubtype))
                            continue
                        if sql:
                            writeFile(fileName, dataNum)
                            mysql_helper.execute(sql, dataNum)
                elif packet_type == 3:
                    while True:
                        fileName = target_path
                        c = f.read(10)
                        if len(c) < 10:
                            break
                        afc = struct.unpack('<7B1H1B', c)
                        operatorid = ''.join([change(i) for i in [afc[k] for k in range(3)]])
                        date_of_occurrence = ''.join([change(i) for i in [afc[k] for k in range(3, 7)]])
                        recorder_len = afc[7]
                        dataNum = ["\t" + file, "\t" + operatorid, "\t" + date_of_occurrence, str(afc[-2]),
                                   str(afc[-1])]
                        d = f.read(17)
                        Particular = struct.unpack('<4B1I9B', d)
                        dataNum.append(str(Particular[0]))
                        dataNum.append("\t" + change(Particular[1]))
                        dataNum.append("\t" + change(Particular[2]))
                        dataNum.append(str(Particular[3]))
                        dataNum.append(str(Particular[4]))
                        dataNum.append("\t" + ''.join([change(i) for i in [Particular[k] for k in range(5, 12)]]))
                        dataNum.append(str(Particular[-2]))
                        dataNum.append(str(Particular[-1]))
                        udType = Particular[-2]
                        udSubtype = Particular[-1]
                        # 3.1.5.1   BOM对TVM故障退款交易——原通道退款
                        if udType == 80 and udSubtype == 1:
                            fileName += '5001.' + date_of_occurrence + '.csv'
                            sql = const.SQL5001
                            e = f.read(19)
                            Equipment_type = struct.unpack('<11B2I', e)
                            dataNum.append(str(Equipment_type[0]))
                            dataNum.append("\t" + change(Equipment_type[1]))
                            dataNum.append("\t" + change(Equipment_type[2]))
                            dataNum.append(str(Equipment_type[3]))
                            dataNum.append(
                                "\t" + ''.join([change(i) for i in [Equipment_type[k] for k in range(4, 11)]]))
                            dataNum.append(str(Equipment_type[-2]))
                            dataNum.append(str(Equipment_type[-1]))
                        # 3.1.5.2   回收已售车票交易
                        elif udType == 80 and udSubtype == 6:
                            fileName += '5006.' + date_of_occurrence + '.csv'
                            sql = const.SQL5006
                            e = f.read(22)
                            cardID = struct.unpack('<1I1H1I1H2I1B', e)
                            for i in cardID:
                                dataNum.append(str(i))
                        # 2.1.5.3   非即时退卡申请交易
                        elif udType == 80 and udSubtype == 2:
                            fileName += '5002.' + date_of_occurrence + '.csv'
                            sql = const.SQL5002
                            e = f.read(11)
                            cardID = struct.unpack('<1I1B1I1H', e)
                            for i in cardID:
                                dataNum.append(str(i))
                            g = f.read(20)
                            cardName = struct.unpack('<20B', g)
                            dataNum.append("\t" + ''.join([chr(i) for i in cardName]))
                            h = f.read(20)
                            cardNo = struct.unpack('<20B', h)
                            dataNum.append("\t" + ''.join([chr(i) for i in cardNo]))
                            j = f.read(1)
                            cardType = struct.unpack('<1B', j)
                            dataNum.append(str(cardType[0]))
                            m = f.read(20)
                            ID_number = struct.unpack('<20B', m)
                            dataNum.append("\t" + ''.join([chr(i) for i in ID_number]))
                            n = f.read(17)
                            deposit = struct.unpack('<2I1B1I4B', n)
                            for i in range(4):
                                dataNum.append(str(deposit[i]))
                            dataNum.append("\t" + ''.join([change(i) for i in [deposit[k] for k in range(4, 8)]]))
                        # 2.1.5.4   无票进出站交易
                        elif udType == 80 and udSubtype == 3:
                            fileName += '5003.' + date_of_occurrence + '.csv'
                            sql = const.SQL5003
                            e = f.read(1)
                            dash = struct.unpack('<1B', e)
                            dataNum.append(str(dash[0]))
                        # 2.1.5.5   TCM使用交易
                        elif udType == 80 and udSubtype == 4:
                            fileName += '5004.' + date_of_occurrence + '.csv'
                            sql = const.SQL5004
                            e = f.read(1)
                            dash = struct.unpack('<1B', e)
                            dataNum.append(str(dash[0]))
                        # 2.1.5.6   废票回收交易
                        elif udType == 80 and udSubtype == 5:
                            fileName += '5005.' + date_of_occurrence + '.csv'
                            sql = const.SQL5005
                            e = f.read(16)
                            dash = struct.unpack('<1I1B1I1H3B1H', e)
                            for i in range(len(dash)):
                                if i == 5:
                                    dataNum.append("\t" + change(dash[i]))
                                else:
                                    dataNum.append(str(dash[i]))
                        else:
                            if recorder_len > 27:
                                e = f.read(recorder_len - 27)
                            # notype.write(FileName+','+str(udType)+','+str(udSubtype)+'\n')
                            log.warning('packet_type=3时: ' + file + ',' + str(udType) + ',' + str(udSubtype))
                            continue
                        if sql:
                            writeFile(fileName, dataNum)
                            mysql_helper.execute(sql, dataNum)
                elif packet_type == 4:
                    while True:
                        dataNum = [file]
                        fileName = target_path
                        c = f.read(32)
                        if len(c) < 32:
                            break
                        Business_data = struct.unpack('<14B1I9B1H3B', c)
                        operatorid = ''.join([change(i) for i in [Business_data[k] for k in range(3)]])
                        date_of_occurrence = ''.join([change(i) for i in [Business_data[k] for k in range(3, 7)]])
                        dataNum = ["\t" + file, "\t" + operatorid, "\t" + date_of_occurrence]
                        dataNum.append(str(Business_data[7]))
                        dataNum.append("\t" + ''.join([change(i) for i in [Business_data[k] for k in range(8, 10)]]))
                        # d = f.read(22)
                        # if len(d) < 22:
                        #    break
                        # Particular = struct.unpack('<4B1I9B1H3B', d)
                        dataNum.append(str(Business_data[10]))
                        dataNum.append("\t" + change(Business_data[11]))
                        dataNum.append("\t" + change(Business_data[12]))
                        dataNum.append(str(Business_data[13]))
                        dataNum.append(str(Business_data[14]))
                        dataNum.append("\t" + ''.join([change(i) for i in [Business_data[k] for k in range(15, 22)]]))
                        dataNum.append(str(Business_data[22]))
                        dataNum.append(str(Business_data[23]))
                        udType = Business_data[22]
                        udSubtype = Business_data[23]
                        recorder_len = Business_data[24]
                        dataNum.append(str(recorder_len))
                        dataNum.append("\t" + ''.join(['{0:0>2}'.format(str(hex(i)).upper()[2:]) for i in
                                                       [Business_data[k] for k in range(25, 28)]]))
                        # recorder_len -= 32
                        # 3.1.6.1   钱箱更换业务数据
                        if udType == 81 and udSubtype == 9:
                            fileName += '5109.' + date_of_occurrence + '.csv'
                            sql = const.SQL5109
                            e = f.read(8)
                            final = struct.unpack('<3B1H3B', e)
                            dataNum.append(str(final[0]))
                            # 注意：3号线报表的钱箱ID的后四位采用十进制，2号线报表的钱箱ID的后四位采用十六进制
                            dataNum.append("\t" + ''.join(['{0:0>2}'.format(str(hex(final[1])).upper()[2:]),
                                                           '{0:0>2}'.format(str(hex(final[2])).upper()[2:]),
                                                           '{0:0>4}'.format(str(hex(final[3])).upper()[2:])]))
                            dataNum.append(str(final[4]))
                            dataNum.append(str(final[5]))
                            rec_nbr = final[6]
                            dataNum.append(str(rec_nbr))
                            # for i in range(len(final)):
                            #    if i == 1:
                            #        dataNum.append("\t"+change(final[i]))
                            #    elif i == 6:
                            #           rec_nbr = final[i]
                            #           dataNum.append(str(rec_nbr))    
                            #    else:
                            #        dataNum.append(str(final[i]))
                            # recorder_len -= 8
                            amount = 0
                            for j in range(rec_nbr):
                                e = f.read(3)
                                final = struct.unpack('<1B1H', e)
                                if final[0] in [17, 49]:
                                    amount += final[1]
                                elif final[0] == 50:
                                    amount += 2 * final[1]
                                elif final[0] == 51:
                                    amount += 5 * final[1]
                                elif final[0] == 52:
                                    amount += 10 * final[1]
                                elif final[0] == 53:
                                    amount += 20 * final[1]
                                elif final[0] == 54:
                                    amount += 50 * final[1]
                                elif final[0] == 55:
                                    amount += 100 * final[1]
                                else:
                                    amount += 0 * final[1]
                                    # dataNum.append(str(final[0]))
                                    # dataNum.append(str(final[1]))
                            dataNum.append(str(amount))
                        # 4.1.5.2	TVM故障退款
                        elif udType == 81 and udSubtype == 1:
                            fileName += '5101.' + date_of_occurrence + '.csv'
                            sql = const.SQL5101
                            e = f.read(35)
                            Equipment_type = struct.unpack('<11B3I12B', e)
                            dataNum.append(str(Equipment_type[0]))
                            dataNum.append("\t" + change(Equipment_type[1]))
                            dataNum.append("\t" + change(Equipment_type[2]))
                            dataNum.append(str(Equipment_type[3]))
                            dataNum.append(
                                "\t" + ''.join([change(i) for i in [Equipment_type[k] for k in range(4, 11)]]))
                            dataNum.append(str(Equipment_type[11]))
                            dataNum.append(str(Equipment_type[12]))
                            dataNum.append(str(Equipment_type[13]))
                            dataNum.append(
                                "\t" + ''.join([change(i) for i in [Equipment_type[k] for k in range(14, 26)]]))
                        # 3.1.6.3   钱箱清点/补充业务数据
                        elif udType == 81 and udSubtype == 21:
                            fileName += '5115.' + date_of_occurrence + '.csv'
                            sql = const.SQL5115
                            e = f.read(10)
                            final = struct.unpack('<3B1H5B', e)
                            dataNum.append(str(final[0]))
                            # 注意：3号线报表的钱箱ID的后四位采用十进制，2号线报表的钱箱ID的后四位采用十六进制
                            dataNum.append("\t" + ''.join(['{0:0>2}'.format(str(hex(final[1])).upper()[2:]),
                                                           '{0:0>2}'.format(str(hex(final[2])).upper()[2:]),
                                                           '{0:0>4}'.format(str(hex(final[3])).upper()[2:])]))
                            for i in range(4, len(final)):
                                if i in [5, 6]:
                                    dataNum.append("\t" + change(final[i]))
                                elif i == 8:
                                    rec_nbr = final[i]
                                    dataNum.append(str(final[i]))
                                else:
                                    dataNum.append(str(final[i]))
                            amount = 0
                            amount_a = 0
                            for j in range(rec_nbr):
                                e = f.read(5)
                                final = struct.unpack('<1B2H', e)
                                if final[0] in [17, 49]:
                                    amount += final[1]
                                    amount_a += final[2]
                                elif final[0] == 50:
                                    amount += 2 * final[1]
                                    amount_a += 2 * final[2]
                                elif final[0] == 51:
                                    amount += 5 * final[1]
                                    amount_a += 5 * final[2]
                                elif final[0] == 52:
                                    amount += 10 * final[1]
                                    amount_a += 10 * final[2]
                                elif final[0] == 53:
                                    amount += 20 * final[1]
                                    amount_a += 20 * final[2]
                                elif final[0] == 54:
                                    amount += 50 * final[1]
                                    amount_a += 50 * final[2]
                                elif final[0] == 55:
                                    amount += 100 * final[1]
                                    amount_a += 100 * final[2]
                                else:
                                    amount += 0 * final[1]
                                    amount_a += 0 * final[2]
                                    # dataNum.append(str(final[0]))
                                    # dataNum.append(str(final[1]))
                                    # dataNum.append(str(final[2]))
                            dataNum.append(str(amount))
                            dataNum.append(str(amount_a))
                        else:
                            if recorder_len > 32:
                                e = f.read(recorder_len - 32)
                            # notype.write(FileName+','+str(udType)+','+str(udSubtype)+'\n')
                            log.warning('packet_type=4时: ' + file + ',' + str(udType) + ',' + str(udSubtype))
                            continue
                        if sql:
                            writeFile(fileName, dataNum)
                            mysql_helper.execute(sql, dataNum)
                else:
                    # notype.write(FileName+'\n')
                    log.info('packet_type无对应类型: ' + file)
                    continue
            except Exception as e:
                log.info('udType: ' + str(udType) + ', udSubtype: ' + str(udSubtype) + ', file: ' + file)
                log.error(e)

    mysql_helper.closeCon()
# if __name__ == '__main__':
#     try:
#         deal = sys.argv[1]
#         if deal not in ['1', '2', '3']:
#             print('请输入正确参数:1-写入文件;2-存mysql数据库;3-同时保村到文件和mysql数据库')
#     except Exception as err:
#         print('请输入正确参数:1-写入文件;2-存mysql数据库;3-同时保村到文件和mysql数据库！错误信息:%s' % err)
#     else:
#         dataDeal(deal)
